<script setup>
import {onMounted, ref} from 'vue'
import http from '@/request/Http'
import {ElMessage} from 'element-plus'

// 公告数据
const announcements = ref([])
const loading = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 公告详情弹窗
const dialogVisible = ref(false)
const currentAnnouncement = ref({})

// 获取公告列表
const getAnnouncements = async () => {
  loading.value = true
  try {
    const params = new URLSearchParams()
    params.append('currentPage', currentPage.value)
    params.append('pageSize', pageSize.value)
    params.append('status', 1) // 只获取启用的公告

    const response = await http.post('/admin/getAnnouncement?' + params.toString())

    if (response.code === 200) {
      announcements.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.msg || '获取公告失败')
    }
  } catch (error) {
    ElMessage.error('获取公告失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 查看公告详情
const viewAnnouncement = (announcement) => {
  currentAnnouncement.value = {...announcement}
  dialogVisible.value = true
}

// 处理分页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getAnnouncements()
}

// 页面加载时获取公告
onMounted(() => {
  getAnnouncements()
})
</script>

<template>
  <div class="system-notice-container">
    <el-card class="notice-card">
      <template #header>
        <div class="card-header">
          <span>系统公告</span>
          <el-icon>
            <Bell/>
          </el-icon>
        </div>
      </template>

      <el-empty v-if="!loading && announcements.length === 0" description="暂无公告"/>

      <div v-else>
        <el-table
            v-loading="loading"
            :data="announcements"
            :show-header="false"
            stripe
            style="width: 100%"
        >
          <el-table-column label="标题" prop="title">
            <template #default="scope">
              <div class="announcement-item" @click="viewAnnouncement(scope.row)">
                <el-tag v-if="isNewAnnouncement(scope.row)" size="small" type="danger">新</el-tag>
                <span class="announcement-title">{{ scope.row.title }}</span>
                <span class="announcement-date">{{ formatDate(scope.row.createdAt) }}</span>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination
            v-if="total > pageSize"
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            class="pagination"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 公告详情弹窗 -->
    <el-dialog v-model="dialogVisible" :title="currentAnnouncement.title" width="600px">
      <div class="announcement-detail">
        <div class="detail-header">
          <el-tag type="info">{{ formatDate(currentAnnouncement.createdAt) }}</el-tag>
        </div>
        <div class="detail-content" v-html="currentAnnouncement.content"></div>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.system-notice-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.notice-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.announcement-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.announcement-item:hover {
  background-color: #f5f7fa;
  padding-left: 10px;
  border-radius: 4px;
}

.announcement-title {
  flex: 1;
  margin-left: 10px;
  color: #303133;
  font-size: 14px;
}

.announcement-date {
  color: #909399;
  font-size: 12px;
  margin-left: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.announcement-detail {
  padding: 20px 0;
}

.detail-header {
  margin-bottom: 15px;
  text-align: right;
}

.detail-content {
  line-height: 1.8;
  white-space: pre-wrap;
  word-wrap: break-word;
}

:deep(.el-dialog__body) {
  padding: 10px 20px 20px;
}

:deep(.el-table__row) {
  cursor: pointer;
}
</style>

<script>
// 辅助函数
export default {
  methods: {
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    // 判断是否为新公告（7天内发布的）
    isNewAnnouncement(announcement) {
      if (!announcement.createdAt) return false
      const createdDate = new Date(announcement.createdAt)
      const now = new Date()
      const diffTime = Math.abs(now - createdDate)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      return diffDays <= 7
    }
  }
}
</script>
